import React, { useEffect } from 'react'
import { useState } from 'react'
import { Button } from 'antd'
import './index.css'
import { array } from 'prop-types'

const Square = ({ onSquareClick, val }) => {
  return (
    <>
      <Button className="square" onClick={onSquareClick}>
        {val}
      </Button>
    </>
  )
}
const Board = () => {
  const [flag, setFlag] = useState(true)
  const [content, setContent] = useState('X')
  const [val, setVal] = useState(Array(9).fill(null))
  const [allData, setAllData] = useState(Array(0).fill(null))
  const list = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [1, 4, 7],
    [2, 5, 8],
    [3, 6, 9],
    [1, 5, 9],
    [3, 5, 7],
  ]

  const handleEdit = (i) => {
    let array = val

    if (array[i] == null) {
      array[i] = content
      setVal(array)
      setFlag(!flag)
    }
    let oldAllData = allData
    oldAllData.push(JSON.parse(JSON.stringify(val)))
    setAllData(oldAllData)
    console.log(oldAllData, 'allData')
    list.some((el) => {
      const avtiveList = []
      el.forEach((item) => {
        avtiveList.push(val[item - 1])
      })

      if (
        avtiveList[0] === avtiveList[1] &&
        avtiveList[1] === avtiveList[2] &&
        avtiveList[0]
      ) {
        setTimeout(() => {
          alert(avtiveList[0] + '赢了')
        }, 500)
      }
    })
  }
  const backData = () => {
    if (allData.length > 1) {
      let oldAllData = allData
      oldAllData.splice(allData.length - 1, 1)
      setAllData(oldAllData)
      setVal(allData[allData.length - 1])
    }
  }
  const rest = () => {
    setAllData([])
    setContent('X')
    setVal(Array(9).fill(null))
  }
  useEffect(() => {
    flag ? setContent('X') : setContent('O')
  })
  return (
    <>
      <div className="board">
        <div className="btnBox">
          <Button type="primary" className="btn" onClick={rest}>
            重 开
          </Button>
          <Button type="primary" className="btn" onClick={backData}>
            悔 棋
          </Button>
        </div>
        <div className="board-row">
          <Square onSquareClick={() => handleEdit(0)} val={val[0]} />
          <Square onSquareClick={() => handleEdit(1)} val={val[1]} />
          <Square onSquareClick={() => handleEdit(2)} val={val[2]} />
        </div>
        <div className="board-row">
          <Square onSquareClick={() => handleEdit(3)} val={val[3]} />
          <Square onSquareClick={() => handleEdit(4)} val={val[4]} />
          <Square onSquareClick={() => handleEdit(5)} val={val[5]} />
        </div>
        <div className="board-row">
          <Square onSquareClick={() => handleEdit(6)} val={val[6]} />
          <Square onSquareClick={() => handleEdit(7)} val={val[7]} />
          <Square onSquareClick={() => handleEdit(8)} val={val[8]} />
        </div>
      </div>
    </>
  )
}
export default Board
